package edu.task.common.security.service;

import edu.task.common.exception.CustomException;
import edu.task.common.exception.user.UserPasswordNotMatchException;
import edu.task.common.security.LoginUser;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.authentication.BadCredentialsException;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.Authentication;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;

/**
 * 校验方法
 */
@Component
public class SysLoginService {
    @Autowired
    private TokenService tokenService;
    @Resource
    private AuthenticationManager authenticationManager;

    /**
     * 登录验证
     * @param userName 用户名
     * @param password 密码
     * @param code 验证码
     * @param uuid 唯一标识
     * @return
     */
    public String login(String userName, String password, String code, String uuid) {
        Authentication authentication=null;
        Boolean flng = false;
        try {
            // 该方法会调用 UserDetailsServiceImpl.loadUserByUsername 方法
            authentication = authenticationManager.authenticate(new UsernamePasswordAuthenticationToken(userName,password));
        }catch (Exception e){
            flng = true;
        }
        if (flng){
            return null;
        }
        LoginUser loginUser= (LoginUser) authentication.getPrincipal();
        // 生成 Token
        return tokenService.createToken(loginUser);
    }
}
